import subprocess
import rrd_base
import re
import time

import color

try:
    from pyrrd.rrd import DataSource, RRA, RRD
    from pyrrd.graph import DEF, CDEF, VDEF
    from pyrrd.graph import LINE, AREA, GPRINT
    from pyrrd.graph import ColorAttributes, Graph
except:
    print "Couldn't load required modules. You probably need to install it with:"
    sys.exit('sudo apt-get install python-pyrrd python-pysnmp4')

class RrdHosts(rrd_base.RrdBase):
    def __init__(self, domain):
        super(RrdHosts,self).__init__(domain=domain, group="net", instance="hosts")

    def create_file(self):
        dataSources = []
        dataSources.append(DataSource( dsName='hosts', dsType='GAUGE', heartbeat=self.heartbeat()))

        roundRobinArchives = []
        for func in ['AVERAGE', 'MAX', 'MIN']:
            for step,row in self.rra_pattern():
                roundRobinArchives.append(RRA(cf=func, xff=0.5, steps=step, rows=row))

        self.myRRD = RRD(self.filename, ds=dataSources, rra=roundRobinArchives, step=self.data_step())
        self.myRRD.create()

    def update(self):
        # /usr/bin/nmap -sP -n 192.168.1.1-254
        nmap = subprocess.Popen(["/usr/bin/nmap", "-sP", "-n", "192.168.1.1-254"], shell=False, stdout=subprocess.PIPE)
        data = nmap.communicate()[0]
        for line in data.split("\n"):
            if re.search("Nmap done: ", line):
                words = re.sub("[(]", " ", line).split()
                self.myRRD.bufferValue(int(round(time.time())), int(words[5]))
                self.myRRD.update()
                break

    def graph(self):
        d_max  = DEF(rrdfile=self.myRRD.filename, vname='d1', dsName='hosts', cdef="MAX")
        d_avg  = DEF(rrdfile=self.myRRD.filename, vname='d0', dsName='hosts', cdef="AVERAGE")
        d_min  = DEF(rrdfile=self.myRRD.filename, vname='d2', dsName='hosts', cdef="MIN")

        v_peak = VDEF(vname='v', rpn="{0},MAXIMUM".format(d_max.vname))

        a_max  = AREA(defObj=d_max,     color=color.RGBA['green'], legend="Maximum")

        l_peak = LINE(1, defObj=v_peak, color=color.RGBA['black'], legend="Peak")
        l_avg  = LINE(1, defObj=d_avg,  color=color.RGB['green'],   legend="Average")
        l_min  = LINE(1, defObj=d_min,  color=color.RGBA['blue'],   legend="Minimum")

        for tf in self.graph_time_frames().keys():
            g = Graph(self.image_name(tf),
                      start=int(time.time())-self.graph_time_frames()[tf], end=int(time.time()),
                      lower_limit=0.000001,
                      title='"Hosts on Local Network - Updated {0}"'.format(time.strftime("%Y%m%d at %H:%M")),
                      vertical_label='Hosts',
                      height=self.graph_height, width=self.graph_width,
                      x_grid=self.grid[tf],
                      step=self.graph_step_times[tf])
            g.data.extend([d_max, v_peak, a_max, l_peak])
            if self.graph_time_frames()[tf] > self.graph_time_frames()["1day"]:
                g.data.extend([d_avg, d_min, l_avg, l_min])
            g.write()

            if False:
                g = Graph(self.icon_name(tf),
                          start=int(time.time())-self.graph_time_frames()[tf], end=int(time.time()),
                          lower_limit=0.000001,
                          no_legend=True,
                          height=self.icon_height, width=self.icon_width,
                          step=self.graph_step_times[tf])
                g.data.extend([d_max, a_max])
                g.write()
